// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "NewAssetFactory.h"
#include "NewAsset.h"
#include "Containers/UnrealString.h"
#include "Misc/FileHelper.h"

UNewAssetFactory::UNewAssetFactory(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
{
	Formats.Add(FString(TEXT("myfile;")));
	SupportedClass = UNewAsset::StaticClass();
	bCreateNew = false;
	bEditorImport = true;
}

UObject* UNewAssetFactory::FactoryCreateFile(UClass* InClass, UObject* InParent,
	FName InName, EObjectFlags Flags, const FString& Filename, const TCHAR* Parms,
	FFeedbackContext* Warn, bool& bOutOperationCanceled)
{
	UNewAsset* NewAsset = nullptr;
	TArray<uint8> Bytes;

	if (FFileHelper::LoadFileToArray(Bytes, *Filename) && Bytes.Num() >= sizeof(int32))
	{
		NewAsset = NewObject<UNewAsset>(InParent, InClass, InName, Flags);
		for (uint32 i = 0; i < sizeof(int32); ++i) {
			NewAsset->IntValue |= Bytes[i] << (i * 8);
		}
	}

	bOutOperationCanceled = false;

	return NewAsset;
}

bool UNewAssetFactory::CanReimport(UObject* Obj, TArray<FString>& OutFilenames)
{
	return true;
}

void UNewAssetFactory::SetReimportPaths(UObject* Obj, const TArray<FString>& NewReimportPaths)
{
	if (IsValid(Obj)) {
		UNewAsset* Asset = Cast<UNewAsset>(Obj);
		if (Asset) {
			UE_LOG(LogTemp, Warning, TEXT(__FUNCTION__ "[%d]"), Asset->IntValue);
		}
	}
	for (auto Path : NewReimportPaths) {
		UE_LOG(LogTemp, Warning, TEXT(__FUNCTION__ "[%s]"), *Path);
	}
}

EReimportResult::Type UNewAssetFactory::Reimport(UObject* Obj)
{
	if (IsValid(Obj)) {
		UNewAsset* Asset = Cast<UNewAsset>(Obj);
		if (Asset) {
			UE_LOG(LogTemp, Warning, TEXT(__FUNCTION__ "[%d]"), Asset->IntValue);
		}
		bool OutCancel = false;
		UObject* NewObj = ImportObject(Obj->GetClass(), Obj->GetOuter(),
			Obj->GetFName(), Obj->GetFlags(), PreferredReimportPath,
			nullptr, OutCancel);
		if (!OutCancel) {
			UNewAsset* NewAsset = Cast<UNewAsset>(NewObj);
			if (NewAsset) {
				UE_LOG(LogTemp, Warning, TEXT(__FUNCTION__ "[%d]"), NewAsset->IntValue);
			}
			return EReimportResult::Succeeded;
		}
	}

	return EReimportResult::Failed;
}
